package com.roc.web.action.terminal;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.common.Excel2007TermFileProcessor;
import com.roc.common.FileProcessor;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.impl.MerchantServiceImpl;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.util.constant.TerminalBrand;
import com.roc.util.constant.TerminalName;
import com.roc.util.constant.TerminalType;
import com.roc.web.action.MerchantSearchCondition;

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/termAllotRecall")
public class TermianlAllotRecallAction extends PaginationBaseAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Logger logger = LogManager.getLogger(TermianlAllotRecallAction.class);
	private TermianlAllotRecallSearchCondition searchCondition;
	private List<OrgBean> orgList=new ArrayList<OrgBean>();
	private Operators merchant;
    private String serialNum;
    private String orgName;
    private String posBrandName ;
    private String posTypeName ;
    private String posName;
    private File upload;
	private YjPosInfo posInfo;

	
    @Autowired
	IPagenitionService pagenitionService;
	@Autowired
	private IorgService orgService;
	@Autowired
	private ITerminalService terminalService;
	@Autowired
	private IMerchantServices merchantServices;
	
	@Action(value = "termAllotRecallInfoJsp",
			results = { @Result(location = "/pages/terminal/terminal_allot_recall.jsp") })
	public String termAllotRecallInfoAction() throws Exception {
		try{
			
			if(posInfo==null||posInfo.getAgentId()<=0){
				addActionMessage("请选择需要撤回终端序列号的代理商");
				return SUCCESS;
			}
			org();
			merchant =merchantServices.loadMerchat(posInfo.getAgentId());
			
		}catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(),e);
			addActionError("基本信息初始化失败");
		}
		return SUCCESS;
	}
	
	@Action(value = "queryTermAllotInfo", results = { @Result(name = "success", location = "/pages/terminal/terminal_allot_recall.jsp")
    })
    //查询可撤回终端序列号信息
	public String queryTermPosInfoAction() throws Exception{
	    Operators loginOperators = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	    List<Long> idList = null;
		if(searchCondition==null){
			searchCondition=(TermianlAllotRecallSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new TermianlAllotRecallSearchCondition();
			}
		}
		try {
			org();
		    merchant=merchantServices.loadMerchat(posInfo.getAgentId());
			if(Role.AGENT.getCode().equals(loginOperators.getRoleType())||Role.O_MANAGER.getCode().equals(loginOperators.getRoleType())){
				searchCondition.setAgentId(loginOperators.getId());
			}else{
				searchCondition.setAgentId(merchant.getId());
			}
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<YjPosInfo> posList= new ArrayList<YjPosInfo>();
			if(searchRsList!=null&&searchRsList.size()>0){
				Iterator iterator=searchRsList.iterator();
				String value = "";
				while (iterator.hasNext()) {
					Object[] obj= (Object[])iterator.next();
					YjPosInfo pos=new YjPosInfo(); 
					pos.setSerialNum(Constance.Null2EmptyTrim(obj[0]));
					pos.setPosBrand(TerminalBrand.valueOfCode(Constance.Null2EmptyTrim(obj[1])).getName());
					pos.setPosType(TerminalType.valueOfCode(Constance.Null2EmptyTrim(obj[2])).getName());
					pos.setPosName(Constance.Null2EmptyTrim(obj[3]));
					pos.setOrgCode(Constance.Null2EmptyTrim(obj[4]));
					pos.setIsBind(Constance.Null2EmptyTrim(obj[5]));
					//pos.setAgentId(Long.valueOf(Constance.Null2EmptyTrim(obj[6])));
					pos.setAgentName(Constance.Null2EmptyTrim(obj[7]));
					pos.setIsUsed(Constance.Null2EmptyTrim(obj[8]));
					pos.setDtCreate((Date)obj[9]);
					pos.setDtLostmod((Date)obj[10]);
					pos.setRemark(Constance.Null2EmptyTrim(obj[11]));
					posList.add(pos);
				}
			}
			searchRsList.clear();
			searchRsList.addAll(posList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下查询到可撤回的终端序列号总计【"+rows+"】个");
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	//终端序列号撤回
	@Action(value = "termianlAllotRecall", results = {
			@Result(name = "success",location = "/pages/terminal/terminal_allot_recall.jsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String termianlAllotRecall() throws Exception{
	    Operators loginOperators = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
	    
	    try{
	    	
	    	org();
	    	merchant=merchantServices.loadMerchat(posInfo.getAgentId());
            if(this.getMulti_sel_str()==null||this.getMulti_sel_str().size()<1){
	    		addActionMessage("请选择需要撤回的终端序列号");
	    		queryTermPosInfoAction();
	    		return SUCCESS;
	    	}
	    	int total=terminalService.terminalAllotRecallBySN(this.getMulti_sel_str(), loginOperators, merchant);
	    	addActionMessage("操作员【"+loginOperators.getAccountNo()+"】成功撤回【"+merchant.getAccountNo()+"】【"+total+"】个终端序列号");
	    	queryTermPosInfoAction();
	    }
	    catch (ServiceException e){
	    	logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
	    }
		return SUCCESS;
	}
	
	private void org(){
		try{
			
			Map<String,String> brandMap=ConfigProperties.getPOSBrand();
			Map<String,String> nameMap=ConfigProperties.getPOSName();
			Map<String,String> typeMap=ConfigProperties.getPOSType();
			getRequest().setAttribute("brandMap", brandMap);
			getRequest().setAttribute("nameMap", nameMap);
			getRequest().setAttribute("typeMap", typeMap);
			
		}catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	protected void dealWithTheListSpecially(List<Object> list) {
		// TODO Auto-generated method stub
		super.dealWithTheListSpecially(list);
		Map<String, String> roleTypes=ConfigProperties.getRoleTypeProperties();
		List<Object> tempList=new ArrayList<Object>();
		for(Object obj:list){
			YjPosInfo pos=(YjPosInfo)obj;
			for(OrgBean bean:orgList){
				if(pos.getOrgCode().equals(bean.getOrg_code())){
					pos.setOrgName(bean.getOrg_name());
				}
			}
			tempList.add(pos);
		}
		searchRsList=tempList;
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_TERMINAL_ALLOT_RECALL, searchCondition);

	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (TermianlAllotRecallSearchCondition)getSession().getAttribute(SEARCH_SESSION_TERMINAL_ALLOT_RECALL);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public String getSerialNum() {
		return serialNum;
	}

	public void setSerialNum(String serialNum) {
		this.serialNum = serialNum;
	}

	public String getOrgName() {
		return orgName;
	}

	public void setOrgName(String orgName) {
		this.orgName = orgName;
	}

	public String getPosBrandName() {
		return posBrandName;
	}

	public void setPosBrandName(String posBrandName) {
		this.posBrandName = posBrandName;
	}

	public String getPosTypeName() {
		return posTypeName;
	}

	public void setPosTypeName(String posTypeName) {
		this.posTypeName = posTypeName;
	}

	public String getPosName() {
		return posName;
	}

	public void setPosName(String posName) {
		this.posName = posName;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public YjPosInfo getPosInfo() {
		return posInfo;
	}

	public void setPosInfo(YjPosInfo posInfo) {
		this.posInfo = posInfo;
	}

	

	public TermianlAllotRecallSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(
			TermianlAllotRecallSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public Operators getMerchant() {
		return merchant;
	}

	public void setMerchant(Operators merchant) {
		this.merchant = merchant;
	}
	
}
